import axios from 'axios';
import errorHandle from './errorHandle';
import { Message, Loading } from 'element-ui';
import { errorCode } from '@/utils/index';

//定义loading变量
let loading = null;

//开始 加载loading
let startLoading = text => {
  loading = Loading.service({
    lock: true,
    spinner: 'el-icon-loading',
    customClass: 'custom-loading',
    text,
    background: 'rgba(0, 0, 0, 0.7)'
  });
};
//结束 取消loading加载
let endLoading = () => {
  loading.close();
};

//showFullScreenLoading() 与 tryHideFullScreenLoading() 目的是合并同一页面多个请求触发loading

// 当前是否有loading实例
let needLoadingRequestCount = 0;

// 打开loading
let showFullScreenLoading = text => {
  if (needLoadingRequestCount === 0) {
    // 当等于0时证明第一次请求 这时开启loading
    startLoading(text);
  }
  needLoadingRequestCount++; //全局变量值++
};

// 关闭loading
let tryHideFullScreenLoading = () => {
  if (needLoadingRequestCount <= 0) return; //小于等于0 证明没有开启loading 此时return
  needLoadingRequestCount--; //正常响应后 全局变量 --
  if (needLoadingRequestCount === 0) {
    //等于0 时证明全部加载完毕 此时结束loading 加载
    endLoading();
  }
};
class HttpRequest {
  // 获取基础配置
  getInsideConfig() {
    const config = {
      //baseURL: process.env.VUE_APP_BASE_API,
      timeout: 10000
    };

    return config;
  }

  // 设定拦截器
  interceptors(instance) {
    // 请求拦截器
    instance.interceptors.request.use(
      config => {
        if (!config.headers.hideLoading) {
          //开启loading加载
          let loadingText = '请求中，请稍候……';
          if (config.headers.loadingText) {
            loadingText = decodeURI(config.headers.loadingText);
          }
          showFullScreenLoading(loadingText);
        }

        if (localStorage.getItem('token')) {
          config.headers.token = localStorage.getItem('token');
        } else {
          config.headers.token =
            'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjo5LCJuYW1lIjoi5byg5LiJIiwiYXZhdGFyIjoiIiwiZXhwIjoxNjI4MzI2Mjc1LCJpc3MiOiJoaWdudG9uIiwibmJmIjoxNjI3ODk0Mjc1fQ.LLIGhkhJcVaLNebWsEPWKro-Tuw_vhU00z4jGWbpfjQ';
        }

        return config;
      },
      err => {
        errorHandle(err);
        return Promise.reject(err);
      }
    );

    // 响应拦截器
    instance.interceptors.response.use(
      res => {
        //关闭loading加载
        tryHideFullScreenLoading();
        if (res.status === 200) {
          let code = res.data.status;
          if (code === 200) {
            return Promise.resolve(res.data);
          } else {
            if (code === 9) {
              //失败后页面有后续操作的
              return Promise.resolve(res.data);
            } else {
              let msg = res.data.message;
              Message({
                type: 'error',
                message: errorCode(msg)
              });
              return Promise.reject(res);
            }
          }
        } else {
          return Promise.reject(res);
        }
      },
      err => {
        //关闭loading加载
        tryHideFullScreenLoading();
        errorHandle(err);
        return Promise.reject(err);
      }
    );
  }

  // 创建实例
  request(options) {
    const instance = axios.create();
    const newOptions = Object.assign(this.getInsideConfig(), options);
    this.interceptors(instance);
    return instance(newOptions);
  }

  // get方法
  get(url, data) {
    const options = Object.assign(
      {
        method: 'get',
        url
      },
      data
    );
    return this.request(options);
  }

  // post方法
  post(url, data) {
    return this.request({
      method: 'post',
      url,
      data
    });
  }

  // put方法
  put(url, data) {
    return this.request({
      method: 'put',
      url,
      data
    });
  }

  // delete方法
  delete(url, data) {
    return this.request({
      method: 'delete',
      url,
      data
    });
  }
}

export default new HttpRequest();
